from sqlalchemy import or_

from server import db, api_auth, user_opt, app_auth

from flask import jsonify, Blueprint, request, g
from server.model.order import Order, OrderStatus
from server.model.app_user import AppUser
from server.model import set_field, query_by_field
import math

from server.utils.send_message import send_order_notification, send_subscription_notification, get_wechat_users
from server.utils.sms import send_normal_sms

a_order = Blueprint('app/order', __name__)


@a_order.route('', methods=['GET'])
@app_auth.login_required
def get_orders():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in order_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        # 先看看登录用户是不是管理员
        if g.user.role == 'admin':
            order_list = Order.query
        else:
            order_list = Order.query.filter(or_(Order.user_id == g.user.id, Order.acceptor_id == g.user.id))

        if query_filter:
            order_list = query_by_field(order_list, query_filter, Order)

        if start_time:
            order_list = order_list.filter(db.cast(Order.create_time, db.Date) >= start_time)

        if end_time:
            order_list = order_list.filter(db.cast(Order.create_time, db.Date) <= end_time)
        total = order_list.count()

        order_list = order_list.offset((page - 1) * limit).limit(limit).all()

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in order_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get orders error:", e)

    return jsonify({'code': 50001, 'message': "查询订单时发生错误"})


@a_order.route('', methods=['POST'])
@app_auth.login_required
def add_order():
    """
    @@@
    #### Args:
            {
                user_id: BIGINT(20    #用户id
                user_name: String(32)    #用户名称
                phone: String(16)    #联系电话
                address: String(200)    #用户名称
                referrer: String(32)    #推荐人
                desc: String(2000)    #办理情况
                acceptor_id: String(2000)    #受理人id
                acceptor_name: String(2000)    #受理人id
                complete_desc: String(2000)    #完成情况
                evaluation: TINYINT    #客户评价，星级
                evaluation_desc: String(2000)    #完成情况
                remark: String(64)    #备注
            }
    #### Returns::
            {'code': 20000, 'message': "订单添加成功"}
            {'code': 50001, 'message': "添加订单时发生错误"}
    """

    args = request.get_json()

    order = Order()
    try:
        set_field(order, args)

        order.user_id = g.user.id
        db.session.add(order)
        db.session.commit()

        admin_users = AppUser.query.filter_by(role='admin').all()
        # 构建要推送的工单信息
        order_info = {
            "id": order.id,
            "user_name": order.user_name,
            "address": order.address,
            "phone": order.phone
        }

        # 调用发送订阅通知的函数
        # send_subscription_notification(admin_users, order_info)
        send_order_notification(admin_users, order_info)

        # for u in admin_users:
        #     res = send_normal_sms(u.phone, order.phone, order.user_name, order.address)
        #     print(res)

        return jsonify({'code': 20000, 'message': "订单添加成功"})
    except Exception as e:
        db.session.rollback()
        print("add order error:", e)

    return jsonify({'code': 50001, 'message': "添加订单时发生错误"})


@a_order.route('/<int:pid>', methods=['DELETE'])
@app_auth.login_required
def remove_order(pid):
    """
        @@@
        #### Args:
                order/id
        #### Returns::
                {'code': 20000, 'message': "订单删除成功"}
                {'code': 50001, 'message': "删除订单时发生错误"}
        """
    try:
        Order.query.filter_by(id=pid).delete()
        db.session.commit()

        user_opt.send({
            "operation": "删除订单",
            "method": "订单管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "订单删除成功"})
    except Exception as e:
        print("remove order error:", e)
        return jsonify({
            'code': 50001,
            'message': "删除订单时发生错误"
        })


@a_order.route('/<int:pid>', methods=['PUT'])
@app_auth.login_required
def edit_order(pid):
    """
    @@@
    #### Args:
           order/id
    #### Returns::
            {'code': 20000, 'message': "订单修改成功"}
            {'code': 50001, 'message': "修改订单时发生错误"}
    """
    args = request.get_json()
    try:
        order = Order.query.filter_by(id=pid).first()
        set_field(order, args)

        # 判断是管理员提交
        if order.status == OrderStatus.Not and g.user.role == 'admin':
            order.status = OrderStatus.Handing

        # 判断是受理员提交
        if order.status == OrderStatus.Handing and g.user.id == order.acceptor_id:
            order.status = OrderStatus.Finished

        db.session.commit()

        return jsonify({'code': 20000, 'message': "订单修改成功"})
    except Exception as e:
        db.session.rollback()
        print("edit order error:", e)

    return jsonify({'code': 50001, 'message': "修改订单时发生错误"})


@a_order.route('/<int:pid>', methods=['GET'])
@app_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           order/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in order_list],
                            }
                """
    order = Order.query.filter_by(id=pid).first()
    if not order:
        return jsonify({
            'code': 50002,
            'message': '查询订单不存在'
        })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': order.to_dict(),
    })
